package com.jiuyun.servlet;

import com.google.gson.Gson;
import com.jiuyun.dao.StudentDao;
import com.jiuyun.dao.impl.StudentDaoImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/json")
public class JsonServlet extends HttpServlet {
    StudentDao dao=new StudentDaoImpl();
    Gson gson=new Gson();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String s=null;
        try {
            List list=dao.getUsers();
            s= gson.toJson(list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //如何让servlet 返回JSON数据
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");//返回json
        PrintWriter out=response.getWriter();
        out.print(s);//数据
        out.flush();
        out.close();
    }
}
